#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>
#include "i2cbar.h"
#include "ping.h"



volatile uint8_t pingDistance;
uint8_t _ping_enabled;
uint8_t _ping_in_progress;
volatile unsigned long _ping_start_ticks;



void pingSetup(void) {

	// set pin to input
	INPUT_PORT_DDR &= ~ ( (1 << PIN_PING) );
	// no ping in progess yet ;-)
	//_ping_in_progress = 0;
	_ping_enabled = 1;
}





volatile uint32_t delta;

void pingLoop(void){
	

	if(_ping_enabled) {
	
		delta =  (timer0GetTicks() - _ping_start_ticks) ;
		if(! _ping_in_progress)	{
			if( delta > 2000UL ) {
		
				// prepare ping
			
				_ping_in_progress = 1;
	
				PORT_OFF(INPUT_PORT, PIN_PING);    // Bring PingPin High for 5us according to spec sheet.
				PORT_ON(INPUT_PORT_DDR, PIN_PING);   // Switch PingPin to OUPUT
				delay_us(2); 
				PORT_ON(INPUT_PORT, PIN_PING);    // Bring PingPin High for 5us according to spec sheet.
				delay_us(5); 
				PORT_OFF(INPUT_PORT, PIN_PING);    
		
				_ping_start_ticks = timer0GetTicks();
				//led2Off();
	
				PORT_OFF(INPUT_PORT_DDR, PIN_PING);   // Switch PingPin to INPUT
				//PORT_OFF(INPUT_PORT, PIN_PING);    // No Pull up
				//PORT_OFF(INPUT_PORT_PIN, PIN_PING);   // ??
			}

		}
		else {
			
			
			if((delta > 840UL) && PORT_IS_OFF(INPUT_PORT_PIN, PIN_PING)) {
				/*
				explanation: 
					dist_in_cm = pic_in_us / 29 / 2  (sonic = 29 us / cm. => both ways  = 58)
					since we have F_CPU = 8000000 and prescale timer0 with 8
					we get 1000000 ticks / s = 1 tick / us
					=> timer0GetTicks() = pic_in_us
				*/
				//pingDistance =  (delta / 58UL) - 14 ;
				
				uint8_t actualMeasure = ((delta / 58UL) - 14UL);
				
				if(actualMeasure < 200) {

					uint16_t oldPingDistance = (uint16_t)pingDistance;
					
					pingDistance = ( oldPingDistance * 7  +  actualMeasure   ) / 8;
					
					if(_buzzer_sound_nr == 7) {
					
						if(pingDistance < 0x60 && abs((int)oldPingDistance - (int)actualMeasure) < 30) {
							BUZZER_START();
							BUZZER_PERIOD(pingDistance+40);
							BUZZER_PULSE(20);
						}
						else
							BUZZER_STOP();
					
					}
				}
				//led2On();	
				_ping_in_progress = 0;
				_ping_start_ticks = timer0GetTicks();
				
				
				
			}
			
		}
	
	}
}












